#include "ThresholdDialog.h"
#include "ThresholdOTSU.h"
#include "ThresholdEntropy.h"
#include "ThresholdManual.h"


ThresholdDialog::ThresholdDialog (QWidget *parent)
: AbstractDialog (parent)
{
	ui.setupUi(this);

	// Add auto threshold presets
	ui.cbPresetSelector->addItem (tr ("Custom"));
	addAutoThresholdPreset (tr ("OTSU"), new ThresholdOTSU ());
	addAutoThresholdPreset (tr ("Entropy"), new ThresholdEntropy ());

}



void ThresholdDialog::handleThresholdValueChanged (int value)
{
	if (ui.spbThreshold->isEnabled ())
		_pAction->setThresholdMethod (new ThresholdManual (value));

	emit thresholdChanged (value);
	emit repaintViewport ();
}



void ThresholdDialog::handlePresetSelected (QString itemName)
{
	if (_pAction == NULL)
		return;
	map< QString, Ptr< ThresholdAuto > >::iterator iter
			= _autoThresholdPresets.find (itemName);
	if (iter != _autoThresholdPresets.end ()) {
		_pAction->setThresholdMethod (iter->second
				.cvt< AbstractThreshold > ());
		ui.sldThreshold->setValue (iter->second->getThresholdValue ());
		ui.sldThreshold->setEnabled (false);
		ui.spbThreshold->setEnabled (false);
	} else {
		_pAction->setThresholdMethod (new ThresholdManual (
				ui.sldThreshold->value ()));
		ui.sldThreshold->setEnabled (true);
		ui.spbThreshold->setEnabled (true);
	}
}



void ThresholdDialog::addAutoThresholdPreset (const QString & name,
											  Ptr< ThresholdAuto > pPreset)
{
	_autoThresholdPresets.insert (make_pair (name, pPreset));
	ui.cbPresetSelector->addItem (name);
}



void ThresholdDialog::_openEvent ()
{
	_pAction = new ThresholdAction (NULL, __pWork);
	int index = ui.cbPresetSelector->findText (tr ("Custom"));
	ui.cbPresetSelector->setCurrentIndex (index);
	handlePresetSelected (tr ("Custom"));
	handleThresholdValueChanged (128);
	__pWork->getDoc ()->openPreview (_pAction.cvt< AbstractAction > ());
	vector< int > histogram = ImageInfo (__pWork->getDoc ()
			->getCurrentLayer ()->getImage ()).getGrayHistogram ();
	map< QString, Ptr< ThresholdAuto > >::iterator iter
		= _autoThresholdPresets.begin ();
	for (; iter != _autoThresholdPresets.end (); ++iter) {
		if (iter->second != NULL)
			iter->second->changeImageInfo (histogram);
	}
	ui.histogramPreviewer->clearChannel ();
	HistogramChannel grayChannel (histogram, QColor (0, 0, 0), 
			tr ("Gray"), true);
	ui.histogramPreviewer->addChannel (grayChannel);
	_pAction->startAction (__pWork);
}

void ThresholdDialog::_closeEvent (int r)
{
	if (r == QDialog::Accepted)
		_pAction->applyAction ();
	else
		_pAction->rejectAction ();
	__pWork->getDoc ()->closePreview ();
	emit repaintViewport ();
}
